package com.qms.qep.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.qms.common.core.controller.BaseController;
import com.qms.common.core.domain.AjaxResult;
import com.qms.common.utils.poi.ExcelUtil;
import com.qms.qep.service.IDataAnalysisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 数据分析Controller
 * 
 * @author qms
 */
@RestController
@RequestMapping("/qep/dataan")
public class DataAnalysisController extends BaseController {
    
    private static final Logger log = LoggerFactory.getLogger(DataAnalysisController.class);

    @Autowired
    private IDataAnalysisService dataAnalysisService;

    /**
     * 获取合格率统计数据
     */
    @GetMapping("/quality/rate")
    public AjaxResult getQualificationRate(
            @RequestParam(required = false) Integer productId,
            @RequestParam(required = false) String productName,
            @RequestParam(required = false) Integer batchId,
            @RequestParam(required = false) String batchNo,
            @RequestParam(required = false) Integer processId,
            @RequestParam(required = false) String processName,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        try {
            Map<String, Object> data = dataAnalysisService.getQualificationRate(productId, productName, batchId, batchNo, processId, processName, startDate, endDate);
            return AjaxResult.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取合格率统计数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取合格率趋势数据
     */
    @GetMapping("/quality/trend")
    public AjaxResult getQualificationTrend(
            @RequestParam(required = false) Integer productId,
            @RequestParam(required = false) String productName,
            @RequestParam(required = false) Integer batchId,
            @RequestParam(required = false) String batchNo,
            @RequestParam(required = false) Integer processId,
            @RequestParam(required = false) String processName,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false, defaultValue = "month") String timeGranularity) {
        try {
            Map<String, Object> data = dataAnalysisService.getQualificationTrend(productId, productName, batchId, batchNo, processId, processName, startDate, endDate, timeGranularity);
            return AjaxResult.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取合格率趋势数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取合格率对比数据
     */
    @GetMapping("/quality/compare")
    public AjaxResult getQualificationCompare(
            @RequestParam String dimension,
            @RequestParam List<Integer> dimensionIds,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        try {
            Map<String, Object> data = dataAnalysisService.getQualificationCompare(dimension, dimensionIds, startDate, endDate);
            return AjaxResult.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取合格率对比数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取缺陷帕累托图数据
     */
    @GetMapping("/defect/pareto")
    public AjaxResult getDefectPareto(
            @RequestParam(required = false) Integer productId,
            @RequestParam(required = false) String productName,
            @RequestParam(required = false) Integer batchId,
            @RequestParam(required = false) String batchNo,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        try {
            Map<String, Object> data = dataAnalysisService.getDefectPareto(productId, productName, batchId, batchNo, startDate, endDate);
            return AjaxResult.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取缺陷帕累托分析失败：" + e.getMessage());
        }
    }

    /**
     * 获取缺陷分布图数据
     */
    @GetMapping("/defect/distribution")
    public AjaxResult getDefectDistribution(
            @RequestParam(required = false) Integer productId,
            @RequestParam(required = false) String productName,
            @RequestParam(required = false) Integer batchId,
            @RequestParam(required = false) String batchNo,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        try {
            Map<String, Object> data = dataAnalysisService.getDefectDistribution(productId, productName, batchId, batchNo, startDate, endDate);
            return AjaxResult.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取缺陷分布数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取TOP缺陷分析数据
     */
    @GetMapping("/defect/top")
    public AjaxResult getDefectTop(
            @RequestParam(required = false) Integer productId,
            @RequestParam(required = false) String productName,
            @RequestParam(required = false) Integer batchId,
            @RequestParam(required = false) String batchNo,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false, defaultValue = "10") Integer limit) {
        try {
            Map<String, Object> data = dataAnalysisService.getDefectTop(productId, productName, batchId, batchNo, startDate, endDate, limit);
            return AjaxResult.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取Top缺陷失败：" + e.getMessage());
        }
    }

    /**
     * 获取维修率统计数据
     */
    @GetMapping("/repair/rate")
    public AjaxResult getRepairRate(
            @RequestParam(required = false) Integer productId,
            @RequestParam(required = false) String productName,
            @RequestParam(required = false) Integer batchId,
            @RequestParam(required = false) String batchNo,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        try {
            Map<String, Object> data = dataAnalysisService.getRepairRate(productId, productName, batchId, batchNo, startDate, endDate);
            return AjaxResult.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取维修率数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取维修成本分析数据
     */
    @GetMapping("/repair/cost")
    public AjaxResult getRepairCost(
            @RequestParam(required = false) Integer productId,
            @RequestParam(required = false) String productName,
            @RequestParam(required = false) Integer batchId,
            @RequestParam(required = false) String batchNo,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        try {
            Map<String, Object> data = dataAnalysisService.getRepairCost(productId, productName, batchId, batchNo, startDate, endDate);
            return AjaxResult.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取维修成本分析失败：" + e.getMessage());
        }
    }

    /**
     * 获取维修效果评估数据
     */
    @GetMapping("/repair/evaluation")
    public AjaxResult getRepairEvaluation(
            @RequestParam(required = false) Integer productId,
            @RequestParam(required = false) String productName,
            @RequestParam(required = false) Integer batchId,
            @RequestParam(required = false) String batchNo,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        try {
            Map<String, Object> data = dataAnalysisService.getRepairEvaluation(productId, productName, batchId, batchNo, startDate, endDate);
            return AjaxResult.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取维修效果评估失败：" + e.getMessage());
        }
    }

    /**
     * 获取过程能力指数(Cp/Cpk)
     */
    @GetMapping("/spc/capability")
    public AjaxResult getProcessCapability(
            @RequestParam(required = false) Integer productId,
            @RequestParam(required = false) String productName,
            @RequestParam(required = false) Integer batchId,
            @RequestParam(required = false) String batchNo,
            @RequestParam(required = false) Integer paramId,
            @RequestParam(required = false) String paramName) {
        try {
            Map<String, Object> data = dataAnalysisService.getProcessCapability(productId, productName, batchId, batchNo, paramId, paramName);
            return AjaxResult.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取过程能力指数失败：" + e.getMessage());
        }
    }

    /**
     * 获取控制图数据
     */
    @GetMapping("/spc/controlchart")
    public AjaxResult getControlChart(
            @RequestParam(required = false) Integer productId,
            @RequestParam(required = false) String productName,
            @RequestParam(required = false) Integer batchId,
            @RequestParam(required = false) String batchNo,
            @RequestParam(required = false) Integer paramId,
            @RequestParam(required = false) String paramName,
            @RequestParam(required = false, defaultValue = "xr") String chartType) {
        try {
            Map<String, Object> data = dataAnalysisService.getControlChart(productId, productName, batchId, batchNo, paramId, paramName, chartType);
            return AjaxResult.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取控制图数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取趋势分析数据
     */
    @GetMapping("/spc/trend")
    public AjaxResult getSpcTrend(
            @RequestParam(required = false) Integer productId,
            @RequestParam(required = false) String productName,
            @RequestParam(required = false) Integer batchId,
            @RequestParam(required = false) String batchNo,
            @RequestParam(required = false) Integer paramId,
            @RequestParam(required = false) String paramName,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        try {
            Map<String, Object> data = dataAnalysisService.getSpcTrend(productId, productName, batchId, batchNo, paramId, paramName, startDate, endDate);
            return AjaxResult.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取SPC趋势分析失败：" + e.getMessage());
        }
    }

    /**
     * 获取产品生命周期追溯
     */
    @GetMapping("/trace/product/{productId}")
    public AjaxResult getProductTrace(@PathVariable Integer productId) {
        try {
            Map<String, Object> data = dataAnalysisService.getProductTrace(productId);
            return AjaxResult.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取产品追溯数据失败：" + e.getMessage());
        }
    }
    
    /**
     * 通过产品名称获取产品生命周期追溯
     */
    @GetMapping("/trace/product/name/{productName}")
    public AjaxResult getProductTraceByName(@PathVariable String productName) {
        try {
            Map<String, Object> data = dataAnalysisService.getProductTraceByName(productName);
            return AjaxResult.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取产品追溯数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取批次追溯
     */
    @GetMapping("/trace/batch/{batchId}")
    public AjaxResult getBatchTrace(@PathVariable Integer batchId) {
        try {
            Map<String, Object> data = dataAnalysisService.getBatchTrace(batchId);
            return AjaxResult.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取批次追溯数据失败：" + e.getMessage());
        }
    }
    
    /**
     * 通过批次号获取批次追溯
     */
    @GetMapping("/trace/batch/no/{batchNo}")
    public AjaxResult getBatchTraceByNo(@PathVariable String batchNo) {
        try {
            Map<String, Object> data = dataAnalysisService.getBatchTraceByNo(batchNo);
            return AjaxResult.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取批次追溯数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取缺陷追溯数据
     */
    @GetMapping("/trace/defect/{defectId}")
    public AjaxResult getDefectTrace(@PathVariable Integer defectId) {
        try {
            Map<String, Object> data = dataAnalysisService.getDefectTrace(defectId);
            return AjaxResult.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取缺陷追溯数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取所有缺陷名称列表，用于下拉框选择
     */
    @GetMapping("/defect/names")
    public AjaxResult getDefectNameList() {
        try {
            Map<String, Object> params = new HashMap<>();
            // 无需特定查询参数，获取所有缺陷名称
            List<Map<String, Object>> defectNames = dataAnalysisService.getDefectNameList();
            return AjaxResult.success(defectNames);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取缺陷名称列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 通过缺陷名称获取缺陷追溯数据
     */
    @GetMapping("/trace/defect/name/{defectName}")
    public AjaxResult getDefectTraceByName(@PathVariable String defectName) {
        try {
            Map<String, Object> data = dataAnalysisService.getDefectTraceByName(defectName);
            return AjaxResult.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取缺陷追溯数据失败：" + e.getMessage());
        }
    }

    /**
     * 导出产品追溯数据
     */
    @PostMapping("/trace/product/export")
    public void exportProductTrace(HttpServletResponse response, @RequestParam String productName) {
        try {
            // 设置响应头，以便前端能够正确处理响应
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = "产品追溯数据_" + productName + "_" + System.currentTimeMillis() + ".xlsx";
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
            
            // 获取产品追溯数据
            Map<String, Object> traceData = dataAnalysisService.getProductTraceByName(productName);
            log.info("导出产品追溯数据: productName={}, traceData大小={}", productName, traceData != null ? traceData.size() : 0);
            
            // 转换为可导出的列表数据
            List<Map<String, Object>> exportData = convertProductTraceToExportData(traceData);
            log.info("导出产品追溯数据: 转换后的exportData大小={}", exportData != null ? exportData.size() : 0);
            
            // 如果没有数据，添加一条提示信息
            if (exportData.isEmpty()) {
                Map<String, Object> emptyInfo = new LinkedHashMap<>();
                emptyInfo.put("提示", "未找到产品 " + productName + " 的追溯数据");
                exportData.add(emptyInfo);
            }
            
            // 导出Excel
            ExcelUtil util = new ExcelUtil(HashMap.class);
            util.exportExcel(response, exportData, "产品追溯数据");
        } catch (Exception e) {
            log.error("导出产品追溯数据失败: {}", e.getMessage(), e);
            e.printStackTrace();
        }
    }
    
    /**
     * 导出批次追溯数据
     */
    @PostMapping("/trace/batch/export")
    public void exportBatchTrace(HttpServletResponse response, @RequestParam String batchNo) {
        try {
            // 设置响应头，以便前端能够正确处理响应
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = "批次追溯数据_" + batchNo + "_" + System.currentTimeMillis() + ".xlsx";
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
            
            // 获取批次追溯数据
            Map<String, Object> traceData = dataAnalysisService.getBatchTraceByNo(batchNo);
            log.info("导出批次追溯数据: batchNo={}, traceData大小={}", batchNo, traceData != null ? traceData.size() : 0);
            
            // 转换为可导出的列表数据
            List<Map<String, Object>> exportData = convertBatchTraceToExportData(traceData);
            log.info("导出批次追溯数据: 转换后的exportData大小={}", exportData != null ? exportData.size() : 0);
            
            // 如果没有数据，添加一条提示信息
            if (exportData.isEmpty()) {
                Map<String, Object> emptyInfo = new LinkedHashMap<>();
                emptyInfo.put("提示", "未找到批次 " + batchNo + " 的追溯数据");
                exportData.add(emptyInfo);
            }
            
            // 导出Excel
            ExcelUtil util = new ExcelUtil(HashMap.class);
            util.exportExcel(response, exportData, "批次追溯数据");
        } catch (Exception e) {
            log.error("导出批次追溯数据失败: {}", e.getMessage(), e);
            e.printStackTrace();
        }
    }
    
    /**
     * 导出缺陷追溯数据
     */
    @PostMapping("/trace/defect/export")
    public void exportDefectTrace(HttpServletResponse response, @RequestParam String defectName) {
        try {
            // 设置响应头，以便前端能够正确处理响应
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = "缺陷追溯数据_" + defectName + "_" + System.currentTimeMillis() + ".xlsx";
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
            
            // 获取缺陷追溯数据
            Map<String, Object> traceData = dataAnalysisService.getDefectTraceByName(defectName);
            log.info("导出缺陷追溯数据: defectName={}, traceData大小={}", defectName, traceData != null ? traceData.size() : 0);
            
            // 转换为可导出的列表数据
            List<Map<String, Object>> exportData = convertDefectTraceToExportData(traceData);
            log.info("导出缺陷追溯数据: 转换后的exportData大小={}", exportData != null ? exportData.size() : 0);
            
            // 如果没有数据，添加一条提示信息
            if (exportData.isEmpty()) {
                Map<String, Object> emptyInfo = new LinkedHashMap<>();
                emptyInfo.put("提示", "未找到缺陷 " + defectName + " 的追溯数据");
                exportData.add(emptyInfo);
            }
            
            // 导出Excel
            ExcelUtil util = new ExcelUtil(HashMap.class);
            util.exportExcel(response, exportData, "缺陷追溯数据");
        } catch (Exception e) {
            log.error("导出缺陷追溯数据失败: {}", e.getMessage(), e);
            e.printStackTrace();
        }
    }
    
    /**
     * 将产品追溯数据转换为可导出的列表数据
     */
    @SuppressWarnings("unchecked")
    private List<Map<String, Object>> convertProductTraceToExportData(Map<String, Object> traceData) {
        List<Map<String, Object>> exportData = new ArrayList<>();
        
        // 如果traceData为空，直接返回空列表
        if (traceData == null || traceData.isEmpty()) {
            log.warn("产品追溯数据为空");
            return exportData;
        }
        
        // 添加导出时间
        Map<String, Object> exportInfo = new LinkedHashMap<>();
        exportInfo.put("数据类型", "导出信息");
        exportInfo.put("导出时间", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        exportData.add(exportInfo);
        
        // 产品基本信息
        if (traceData.containsKey("product") && traceData.get("product") != null) {
            Map<String, Object> product = (Map<String, Object>) traceData.get("product");
            Map<String, Object> productInfo = new LinkedHashMap<>();
            productInfo.put("数据类型", "产品基本信息");
            productInfo.put("产品名称", product.getOrDefault("productName", ""));
            productInfo.put("产品编号", product.getOrDefault("productCode", ""));
            productInfo.put("规格型号", product.getOrDefault("specification", ""));
            productInfo.put("版本", product.getOrDefault("version", ""));
            productInfo.put("创建时间", product.getOrDefault("createTime", ""));
            productInfo.put("状态", product.getOrDefault("status", ""));
            exportData.add(productInfo);
        } else {
            log.warn("产品基本信息为空");
        }
        
        // 生命周期记录
        if (traceData.containsKey("lifecycle") && traceData.get("lifecycle") != null) {
            List<Map<String, Object>> lifecycle = (List<Map<String, Object>>) traceData.get("lifecycle");
            if (lifecycle != null && !lifecycle.isEmpty()) {
                for (Map<String, Object> activity : lifecycle) {
                    Map<String, Object> activityInfo = new LinkedHashMap<>();
                    activityInfo.put("数据类型", "生命周期记录");
                    activityInfo.put("活动时间", activity.getOrDefault("timestamp", ""));
                    activityInfo.put("活动标题", activity.getOrDefault("title", ""));
                    activityInfo.put("活动描述", activity.getOrDefault("description", ""));
                    activityInfo.put("操作人", activity.getOrDefault("operator", ""));
                    exportData.add(activityInfo);
                }
            } else {
                log.warn("生命周期记录为空");
            }
        }
        
        // 原料批次追溯
        if (traceData.containsKey("materials") && traceData.get("materials") != null) {
            List<Map<String, Object>> materials = (List<Map<String, Object>>) traceData.get("materials");
            if (materials != null && !materials.isEmpty()) {
                for (Map<String, Object> material : materials) {
                    Map<String, Object> materialInfo = new LinkedHashMap<>();
                    materialInfo.put("数据类型", "原料批次");
                    materialInfo.put("原料名称", material.getOrDefault("materialName", ""));
                    materialInfo.put("规格", material.getOrDefault("specification", ""));
                    materialInfo.put("批次号", material.getOrDefault("batchNo", ""));
                    materialInfo.put("供应商", material.getOrDefault("supplier", ""));
                    materialInfo.put("入库时间", material.getOrDefault("receiveTime", ""));
                    materialInfo.put("使用数量", material.getOrDefault("quantity", ""));
                    materialInfo.put("状态", material.getOrDefault("status", ""));
                    exportData.add(materialInfo);
                }
            } else {
                log.warn("原料批次追溯为空");
            }
        }
        
        // 生产过程追溯
        if (traceData.containsKey("processes") && traceData.get("processes") != null) {
            List<Map<String, Object>> processes = (List<Map<String, Object>>) traceData.get("processes");
            if (processes != null && !processes.isEmpty()) {
                for (Map<String, Object> process : processes) {
                    Map<String, Object> processInfo = new LinkedHashMap<>();
                    processInfo.put("数据类型", "生产过程");
                    processInfo.put("工序名称", process.getOrDefault("processName", ""));
                    processInfo.put("工序编号", process.getOrDefault("processCode", ""));
                    processInfo.put("开始时间", process.getOrDefault("startTime", ""));
                    processInfo.put("完成时间", process.getOrDefault("endTime", ""));
                    processInfo.put("操作员", process.getOrDefault("operator", ""));
                    processInfo.put("设备", process.getOrDefault("equipment", ""));
                    processInfo.put("结果", process.getOrDefault("result", ""));
                    exportData.add(processInfo);
                    
                    // 参数记录
                    if (process.containsKey("parameters") && process.get("parameters") != null) {
                        List<Map<String, Object>> parameters = (List<Map<String, Object>>) process.get("parameters");
                        if (parameters != null && !parameters.isEmpty()) {
                            for (Map<String, Object> parameter : parameters) {
                                Map<String, Object> parameterInfo = new LinkedHashMap<>();
                                parameterInfo.put("数据类型", "参数记录");
                                parameterInfo.put("工序名称", process.getOrDefault("processName", ""));
                                parameterInfo.put("参数名称", parameter.getOrDefault("paramName", ""));
                                parameterInfo.put("测量值", parameter.getOrDefault("value", ""));
                                parameterInfo.put("标准值", parameter.getOrDefault("standardValue", ""));
                                parameterInfo.put("公差", parameter.getOrDefault("tolerance", ""));
                                parameterInfo.put("状态", parameter.getOrDefault("status", ""));
                                parameterInfo.put("测量时间", parameter.getOrDefault("measureTime", ""));
                                exportData.add(parameterInfo);
                            }
                        }
                    }
                    
                    // 缺陷记录
                    if (process.containsKey("defects") && process.get("defects") != null) {
                        List<Map<String, Object>> defects = (List<Map<String, Object>>) process.get("defects");
                        if (defects != null && !defects.isEmpty()) {
                            for (Map<String, Object> defect : defects) {
                                Map<String, Object> defectInfo = new LinkedHashMap<>();
                                defectInfo.put("数据类型", "缺陷记录");
                                defectInfo.put("工序名称", process.getOrDefault("processName", ""));
                                defectInfo.put("缺陷编号", defect.getOrDefault("defectCode", ""));
                                defectInfo.put("缺陷类型", defect.getOrDefault("defectName", ""));
                                defectInfo.put("严重程度", defect.getOrDefault("severity", ""));
                                defectInfo.put("描述", defect.getOrDefault("description", ""));
                                defectInfo.put("发现时间", defect.getOrDefault("findTime", ""));
                                exportData.add(defectInfo);
                            }
                        }
                    }
                }
            } else {
                log.warn("生产过程追溯为空");
            }
        }
        
        // 检验记录
        if (traceData.containsKey("inspections") && traceData.get("inspections") != null) {
            List<Map<String, Object>> inspections = (List<Map<String, Object>>) traceData.get("inspections");
            if (inspections != null && !inspections.isEmpty()) {
                for (Map<String, Object> inspection : inspections) {
                    Map<String, Object> inspectionInfo = new LinkedHashMap<>();
                    inspectionInfo.put("数据类型", "检验记录");
                    inspectionInfo.put("检验单号", inspection.getOrDefault("inspectionNo", ""));
                    inspectionInfo.put("检验类型", inspection.getOrDefault("inspectionType", ""));
                    inspectionInfo.put("检验员", inspection.getOrDefault("inspector", ""));
                    inspectionInfo.put("检验时间", inspection.getOrDefault("inspectionTime", ""));
                    inspectionInfo.put("检验结果", inspection.getOrDefault("result", ""));
                    exportData.add(inspectionInfo);
                }
            } else {
                log.warn("检验记录为空");
            }
        }
        
        return exportData;
    }
    
    /**
     * 将批次追溯数据转换为可导出的列表数据
     */
    @SuppressWarnings("unchecked")
    private List<Map<String, Object>> convertBatchTraceToExportData(Map<String, Object> traceData) {
        List<Map<String, Object>> exportData = new ArrayList<>();
        
        // 如果traceData为空，直接返回空列表
        if (traceData == null || traceData.isEmpty()) {
            log.warn("批次追溯数据为空");
            return exportData;
        }
        
        // 添加导出时间
        Map<String, Object> exportInfo = new LinkedHashMap<>();
        exportInfo.put("数据类型", "导出信息");
        exportInfo.put("导出时间", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        exportData.add(exportInfo);
        
        // 批次基本信息
        if (traceData.containsKey("batch") && traceData.get("batch") != null) {
            Map<String, Object> batch = (Map<String, Object>) traceData.get("batch");
            Map<String, Object> batchInfo = new LinkedHashMap<>();
            batchInfo.put("数据类型", "批次基本信息");
            batchInfo.put("批次编号", batch.getOrDefault("batchNo", ""));
            batchInfo.put("产品名称", batch.getOrDefault("productName", ""));
            batchInfo.put("产品编号", batch.getOrDefault("productCode", ""));
            batchInfo.put("计划数量", batch.getOrDefault("planQuantity", ""));
            batchInfo.put("实际数量", batch.getOrDefault("actualQuantity", ""));
            batchInfo.put("开始时间", batch.getOrDefault("startTime", ""));
            batchInfo.put("完成时间", batch.getOrDefault("endTime", ""));
            batchInfo.put("状态", batch.getOrDefault("status", ""));
            exportData.add(batchInfo);
        } else {
            log.warn("批次基本信息为空");
        }
        
        // 质量统计
        if (traceData.containsKey("stats") && traceData.get("stats") != null) {
            Map<String, Object> stats = (Map<String, Object>) traceData.get("stats");
            if (!stats.isEmpty()) {
                Map<String, Object> statsInfo = new LinkedHashMap<>();
                statsInfo.put("数据类型", "质量统计");
                statsInfo.put("合格率", stats.getOrDefault("qualificationRate", ""));
                statsInfo.put("一次通过率", stats.getOrDefault("firstPassRate", ""));
                statsInfo.put("缺陷密度", stats.getOrDefault("defectDensity", ""));
                statsInfo.put("检验数量", stats.getOrDefault("inspectedQuantity", ""));
                statsInfo.put("合格数量", stats.getOrDefault("qualifiedQuantity", ""));
                statsInfo.put("首次合格数量", stats.getOrDefault("firstPassQuantity", ""));
                statsInfo.put("缺陷数", stats.getOrDefault("defectCount", ""));
                exportData.add(statsInfo);
            } else {
                log.warn("质量统计为空");
            }
        }
        
        // 工序进度
        if (traceData.containsKey("processes") && traceData.get("processes") != null) {
            List<Map<String, Object>> processes = (List<Map<String, Object>>) traceData.get("processes");
            if (processes != null && !processes.isEmpty()) {
                for (Map<String, Object> process : processes) {
                    Map<String, Object> processInfo = new LinkedHashMap<>();
                    processInfo.put("数据类型", "工序进度");
                    processInfo.put("工序名称", process.getOrDefault("processName", ""));
                    processInfo.put("开始时间", process.getOrDefault("startTime", ""));
                    processInfo.put("完成时间", process.getOrDefault("endTime", ""));
                    processInfo.put("状态", process.getOrDefault("status", ""));
                    processInfo.put("进度", process.getOrDefault("progress", ""));
                    exportData.add(processInfo);
                }
            } else {
                log.warn("工序进度为空");
            }
        }
        
        // 检验记录
        if (traceData.containsKey("inspections") && traceData.get("inspections") != null) {
            List<Map<String, Object>> inspections = (List<Map<String, Object>>) traceData.get("inspections");
            if (inspections != null && !inspections.isEmpty()) {
                for (Map<String, Object> inspection : inspections) {
                    Map<String, Object> inspectionInfo = new LinkedHashMap<>();
                    inspectionInfo.put("数据类型", "检验记录");
                    inspectionInfo.put("检验单号", inspection.getOrDefault("inspectionNo", ""));
                    inspectionInfo.put("检验类型", inspection.getOrDefault("inspectionType", ""));
                    inspectionInfo.put("检验员", inspection.getOrDefault("inspector", ""));
                    inspectionInfo.put("检验时间", inspection.getOrDefault("inspectionTime", ""));
                    inspectionInfo.put("检验结果", inspection.getOrDefault("result", ""));
                    inspectionInfo.put("检验项数", inspection.getOrDefault("itemsCount", ""));
                    exportData.add(inspectionInfo);
                }
            } else {
                log.warn("检验记录为空");
            }
        }
        
        // 异常记录
        if (traceData.containsKey("defects") && traceData.get("defects") != null) {
            List<Map<String, Object>> defects = (List<Map<String, Object>>) traceData.get("defects");
            if (defects != null && !defects.isEmpty()) {
                for (Map<String, Object> defect : defects) {
                    Map<String, Object> defectInfo = new LinkedHashMap<>();
                    defectInfo.put("数据类型", "异常记录");
                    defectInfo.put("缺陷编号", defect.getOrDefault("defectCode", ""));
                    defectInfo.put("缺陷类型", defect.getOrDefault("defectName", ""));
                    defectInfo.put("发生工序", defect.getOrDefault("processName", ""));
                    defectInfo.put("发现时间", defect.getOrDefault("findTime", ""));
                    defectInfo.put("严重程度", defect.getOrDefault("severity", ""));
                    defectInfo.put("状态", defect.getOrDefault("status", ""));
                    exportData.add(defectInfo);
                }
            } else {
                log.warn("异常记录为空");
            }
        }
        
        // 影响范围评估 - 相关批次
        if (traceData.containsKey("impactAssessment") && traceData.get("impactAssessment") != null) {
            Map<String, Object> impact = (Map<String, Object>) traceData.get("impactAssessment");
            
            if (impact.containsKey("relatedBatches") && impact.get("relatedBatches") != null) {
                List<Map<String, Object>> batches = (List<Map<String, Object>>) impact.get("relatedBatches");
                if (batches != null && !batches.isEmpty()) {
                    for (Map<String, Object> batch : batches) {
                        Map<String, Object> batchInfo = new LinkedHashMap<>();
                        batchInfo.put("数据类型", "相关批次");
                        batchInfo.put("批次号", batch.getOrDefault("batchNo", ""));
                        batchInfo.put("产品名称", batch.getOrDefault("productName", ""));
                        batchInfo.put("关联类型", batch.getOrDefault("relation", ""));
                        batchInfo.put("生产时间", batch.getOrDefault("startTime", ""));
                        batchInfo.put("状态", batch.getOrDefault("status", ""));
                        exportData.add(batchInfo);
                    }
                }
            }
            
            // 影响范围评估 - 相关工艺
            if (impact.containsKey("relatedProcesses") && impact.get("relatedProcesses") != null) {
                List<Map<String, Object>> processes = (List<Map<String, Object>>) impact.get("relatedProcesses");
                if (processes != null && !processes.isEmpty()) {
                    for (Map<String, Object> process : processes) {
                        Map<String, Object> processInfo = new LinkedHashMap<>();
                        processInfo.put("数据类型", "相关工艺");
                        processInfo.put("工艺名称", process.getOrDefault("processName", ""));
                        processInfo.put("工艺编号", process.getOrDefault("processCode", ""));
                        processInfo.put("关联类型", process.getOrDefault("relation", ""));
                        processInfo.put("影响程度", process.getOrDefault("impactLevel", ""));
                        processInfo.put("建议", process.getOrDefault("recommendation", ""));
                        exportData.add(processInfo);
                    }
                }
            }
            
            // 影响范围评估 - 潜在风险
            if (impact.containsKey("potentialRisks") && impact.get("potentialRisks") != null) {
                List<Map<String, Object>> risks = (List<Map<String, Object>>) impact.get("potentialRisks");
                if (risks != null && !risks.isEmpty()) {
                    for (Map<String, Object> risk : risks) {
                        Map<String, Object> riskInfo = new LinkedHashMap<>();
                        riskInfo.put("数据类型", "潜在风险");
                        riskInfo.put("风险名称", risk.getOrDefault("riskName", ""));
                        riskInfo.put("风险类别", risk.getOrDefault("category", ""));
                        riskInfo.put("发生概率", risk.getOrDefault("probability", ""));
                        riskInfo.put("严重程度", risk.getOrDefault("severity", ""));
                        riskInfo.put("缓解措施", risk.getOrDefault("mitigation", ""));
                        exportData.add(riskInfo);
                    }
                }
            }
        }
        
        return exportData;
    }
    
    /**
     * 将缺陷追溯数据转换为可导出的列表数据
     */
    @SuppressWarnings("unchecked")
    private List<Map<String, Object>> convertDefectTraceToExportData(Map<String, Object> traceData) {
        List<Map<String, Object>> exportData = new ArrayList<>();
        
        // 如果traceData为空，直接返回空列表
        if (traceData == null || traceData.isEmpty()) {
            log.warn("缺陷追溯数据为空");
            return exportData;
        }
        
        // 添加导出时间
        Map<String, Object> exportInfo = new LinkedHashMap<>();
        exportInfo.put("数据类型", "导出信息");
        exportInfo.put("导出时间", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        exportData.add(exportInfo);
        
        // 缺陷基本信息
        if (traceData.containsKey("defect") && traceData.get("defect") != null) {
            Map<String, Object> defect = (Map<String, Object>) traceData.get("defect");
            Map<String, Object> defectInfo = new LinkedHashMap<>();
            defectInfo.put("数据类型", "缺陷基本信息");
            defectInfo.put("缺陷编号", defect.getOrDefault("defectCode", ""));
            defectInfo.put("缺陷类型", defect.getOrDefault("defectName", ""));
            defectInfo.put("产品名称", defect.getOrDefault("productName", ""));
            defectInfo.put("批次编号", defect.getOrDefault("batchNo", ""));
            defectInfo.put("发现工序", defect.getOrDefault("processName", ""));
            defectInfo.put("发现时间", defect.getOrDefault("findTime", ""));
            defectInfo.put("报告人", defect.getOrDefault("reporter", ""));
            defectInfo.put("缺陷状态", defect.getOrDefault("status", ""));
            defectInfo.put("缺陷描述", defect.getOrDefault("description", ""));
            exportData.add(defectInfo);
        } else {
            log.warn("缺陷基本信息为空");
        }
        
        // 根本原因分析
        if (traceData.containsKey("rca") && traceData.get("rca") != null) {
            Map<String, Object> rca = (Map<String, Object>) traceData.get("rca");
            
            // 根本原因
            if (rca.containsKey("rootCause") && rca.get("rootCause") != null) {
                Map<String, Object> rootCause = (Map<String, Object>) rca.get("rootCause");
                if (!rootCause.isEmpty()) {
                    Map<String, Object> rootCauseInfo = new LinkedHashMap<>();
                    rootCauseInfo.put("数据类型", "根本原因");
                    rootCauseInfo.put("标题", rootCause.getOrDefault("title", ""));
                    rootCauseInfo.put("描述", rootCause.getOrDefault("description", ""));
                    exportData.add(rootCauseInfo);
                }
            }
            
            // 原因分类
            if (rca.containsKey("causes") && rca.get("causes") != null) {
                List<Map<String, Object>> causes = (List<Map<String, Object>>) rca.get("causes");
                if (causes != null && !causes.isEmpty()) {
                    for (Map<String, Object> category : causes) {
                        String categoryName = (String) category.getOrDefault("category", "未知类别");
                        
                        if (category.containsKey("items") && category.get("items") != null) {
                            List<Map<String, Object>> items = (List<Map<String, Object>>) category.get("items");
                            if (items != null && !items.isEmpty()) {
                                for (Map<String, Object> item : items) {
                                    Map<String, Object> causeInfo = new LinkedHashMap<>();
                                    causeInfo.put("数据类型", "原因分析");
                                    causeInfo.put("类别", categoryName);
                                    causeInfo.put("原因", item.getOrDefault("cause", ""));
                                    causeInfo.put("可能性", item.getOrDefault("probability", ""));
                                    causeInfo.put("验证状态", item.containsKey("verified") && (Boolean)item.get("verified") ? "已验证" : "未验证");
                                    exportData.add(causeInfo);
                                }
                            }
                        }
                    }
                }
            }
        }
        
        // 纠正措施
        if (traceData.containsKey("correctiveActions") && traceData.get("correctiveActions") != null) {
            List<Map<String, Object>> actions = (List<Map<String, Object>>) traceData.get("correctiveActions");
            if (actions != null && !actions.isEmpty()) {
                for (Map<String, Object> action : actions) {
                    Map<String, Object> actionInfo = new LinkedHashMap<>();
                    actionInfo.put("数据类型", "纠正措施");
                    actionInfo.put("标题", action.getOrDefault("title", ""));
                    actionInfo.put("描述", action.getOrDefault("description", ""));
                    actionInfo.put("状态", action.getOrDefault("status", ""));
                    exportData.add(actionInfo);
                }
            } else {
                log.warn("纠正措施为空");
            }
        }
        
        // 预防措施
        if (traceData.containsKey("preventiveActions") && traceData.get("preventiveActions") != null) {
            List<Map<String, Object>> actions = (List<Map<String, Object>>) traceData.get("preventiveActions");
            if (actions != null && !actions.isEmpty()) {
                for (Map<String, Object> action : actions) {
                    Map<String, Object> actionInfo = new LinkedHashMap<>();
                    actionInfo.put("数据类型", "预防措施");
                    actionInfo.put("类型", action.getOrDefault("type", ""));
                    actionInfo.put("措施内容", action.getOrDefault("action", ""));
                    actionInfo.put("负责部门", action.getOrDefault("department", ""));
                    actionInfo.put("负责人", action.getOrDefault("owner", ""));
                    actionInfo.put("截止日期", action.getOrDefault("deadline", ""));
                    actionInfo.put("状态", action.getOrDefault("status", ""));
                    exportData.add(actionInfo);
                }
            } else {
                log.warn("预防措施为空");
            }
        }
        
        // 相似缺陷
        if (traceData.containsKey("similarDefects") && traceData.get("similarDefects") != null) {
            List<Map<String, Object>> defects = (List<Map<String, Object>>) traceData.get("similarDefects");
            if (defects != null && !defects.isEmpty()) {
                for (Map<String, Object> defect : defects) {
                    Map<String, Object> defectInfo = new LinkedHashMap<>();
                    defectInfo.put("数据类型", "相似缺陷");
                    defectInfo.put("缺陷编号", defect.getOrDefault("defectCode", ""));
                    defectInfo.put("缺陷类型", defect.getOrDefault("defectName", ""));
                    defectInfo.put("产品", defect.getOrDefault("productName", ""));
                    defectInfo.put("批次", defect.getOrDefault("batchNo", ""));
                    defectInfo.put("发现时间", defect.getOrDefault("findTime", ""));
                    defectInfo.put("相似度", defect.getOrDefault("similarity", ""));
                    exportData.add(defectInfo);
                }
            } else {
                log.warn("相似缺陷为空");
            }
        }
        
        return exportData;
    }
}